import { Component, OnInit, ViewChild } from '@angular/core';
import { IonContent, NavController } from '@ionic/angular';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpService } from '../shared/service/http.service';
import { AppGlobalService } from '../shared/service/app-global.service';
import { PageModalService } from '../shared/service/page-modal-service';
@Component({
  selector: 'app-qr-code-scanner',
  templateUrl: './qr-code-scanner.page.html',
  styleUrls: ['./qr-code-scanner.page.scss'],
})
export class QrCodeScannerPage implements OnInit {

  light: boolean; // 判断闪光灯
  frontCamera: boolean; // 判断摄像头
  isShow = false; // 控制显示背景，避免切换页面卡顿


  // 标题
  pageTitle: any;

  // 解析page接口中的submit
  submit: any;

  // 当前操作类型 'submit'、'link'
  action: any;

  // 路由参数
  routerParams: any;

  titleBar: any; // 2024.06.28 新增
  @ViewChild(IonContent) content: IonContent;
  bgCssStyle: any;
  qrscannerAreaCssStyle: any;
  throughLineCssStyle: any;
  buttonBottomCssStyle: any;
  iconLightCssStyle: any;
  iconCameraCssStyle: any;
  flashCssStyle: any;
  reverseCssStyle: any;


  // 2.3.5 submit提交成功之后需要跳转到page
  jumpPageAfterSubmit = false; // 默认是false
  linkType = 'page'; // 默认为page
  modalCss = 'auto-modal';
  cssStyle = '';

  constructor(
    public router: Router,
    private qrScanner: QRScanner,
    public navController: NavController,
    private httpService: HttpService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private route: ActivatedRoute) { }
  ngOnInit() {

    const that = this;
    console.log('ngOnInit .. qrcodeScanner');
    this.route.queryParams.subscribe(p => {
      let paramsStr: any;
      if (p.params) {
        paramsStr = JSON.parse(p.params);
        this.pageTitle = paramsStr.pageTitle;
      }
      if (paramsStr) {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          // tslint:disable-next-line:radix
          pageId: parseInt(paramsStr.pageTargetId),
          params: paramsStr
        };
        this.routerParams = paramsStr;
        this.httpService.post('application/page', params, async res => {
          let pageData;
          if (res && res.script && JSON.parse(res.script)) {
            pageData = JSON.parse(res.script);
            that.titleBar = pageData.titleBar;
            this.bgCssStyle = pageData.bgCssStyle;
            const ionScroll = await this.content.getScrollElement();
            ionScroll.style.background = this.bgCssStyle;
          }
          console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  pageData=	   ', pageData);
          this.pageModalService.getPageTagDataWithPageRes(res, data => {
            console.log('getPageTagDataWithPageRes=', data);
            if (data && data.length > 0) {
              // 取data中的submit
              data.forEach((i, index) => {
                if (i.action === 'qrcodeScanner') {
                  this.submit = i.submit;
                  this.action = 'qrcodeScanner';
                }
                if (index === 0) {
                  if (i.qrscannerAreaCssStyle) {
                    that.qrscannerAreaCssStyle = i.qrscannerAreaCssStyle;
                  } else if (i.throughLineCssStyle) {
                    that.throughLineCssStyle = i.throughLineCssStyle;
                  } else if (i.buttonBottomCssStyle) {
                    that.buttonBottomCssStyle = i.buttonBottomCssStyle;
                  } else if (i.iconLightCssStyle) {
                    that.iconLightCssStyle = i.iconLightCssStyle;
                  } else if (i.iconCameraCssStyle) {
                    that.iconCameraCssStyle = i.iconCameraCssStyle;
                  } else if (i.flashCssStyle) {
                    that.flashCssStyle = i.flashCssStyle;
                  } else if (i.reverseCssStyle) {
                    that.reverseCssStyle = i.reverseCssStyle;
                  }
                }

                if (i.jumpPageAfterSubmit && i.jumpPageAfterSubmit === 'true') {
                  this.jumpPageAfterSubmit = true;
                }
                if (i.linkType) {
                  this.linkType = i.linkType;
                }
                if (i.modalCss) {
                  this.modalCss = i.modalCss;
                }
                if (i.cssStyle) {
                  this.cssStyle = i.cssStyle;
                }
              });
            } else if (data && data.action !== undefined && data.action === 'link') {
              this.action = 'link';
              this.submit = data.linkButton;
              console.log('submit', this.submit);
            }
          });
        });
      }
    });
  }

  // 确定提交表单用
  textButton(textButton, searchInput?) {
    this.check(textButton);
  }

  check(textButton) {

  }

  searchButtonClick(obj, ite?, e?) {

    // 2024.04.12 新增参数联调
    if (obj.link && obj.link.params
      && obj.link.params.key
      && obj.link.params.key.hasOwnProperty('latitude')
      && obj.link.params.key.hasOwnProperty('longitude')) {
      const position = JSON.parse(localStorage.getItem('position'));
      obj.link.params.key.latitude = position.center.lat;
      obj.link.params.key.longitude = position.center.lng;
      if (obj.link.params.key.useSelectedPosition !== undefined) {
        if (this.appGlobalService.searchShopLat !== undefined) {
          obj.link.params.key.latitude =
            this.appGlobalService.getAddressLat ? this.appGlobalService.getAddressLat : this.appGlobalService.searchShopLat;
        }
        if (this.appGlobalService.searchShopLng !== undefined) {
          obj.link.params.key.longitude =
            this.appGlobalService.getAddressLng ? this.appGlobalService.getAddressLng : this.appGlobalService.searchShopLng;
        }

      }
    }
    if (obj.searchType === '200') {

    }
    if (obj.searchType === '300') {
      if (e) {
        e.stopPropagation();
      }
      const searchPath = '/navSearch';

      const tempObj = JSON.parse(JSON.stringify(obj));
      this.clearCssStyleParam(tempObj);

      this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(tempObj), ite } });
      return;
    }
    if (obj.partLink && obj.partLink.params && obj.partLink.params.key && obj.partLink.params.key.searchButtonCssStyle) {
      if (document.getElementsByTagName('app-nav-one')) {
        const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < navOneCollection.length; i++) {
          const el = navOneCollection[i];
          if (!this.hasClass(el, 'ion-page-hidden')) {
            const bottomSearch = el.getElementsByClassName('bottomSearchBox')[0] as HTMLElement;
            const searchDiv = bottomSearch.children[0] as HTMLElement;
            searchDiv.click();
            break;
          }
        }
      }
    } else {
      // search res back to search history
      if (obj.goTo && obj.goTo === "-1") {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      } else {

        if (this.titleBar
          && this.titleBar.link
          && this.titleBar.link.link
          && this.titleBar.link.link.params
          && this.titleBar.link.link.params.useTitleBarLink !== undefined
        ) {
          this.pageModalService.openPage(this.titleBar.link.link);
        } else {
          // to history page
          console.log('to search history');
          localStorage.removeItem('searchParams');
          localStorage.removeItem('invitationArr');
          const searchPath = '/navSearch';
          const tempObj = JSON.parse(JSON.stringify(obj));
          this.clearCssStyleParam(tempObj);
          this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(tempObj) } });
        }

      }
    }
  }

  clearCssStyleParam(obj) {
    if (obj && obj.link.params.key && obj.link.params.key.buttonCssStyle) {
      delete obj.link.params.key.buttonCssStyle;
    }
    if (obj && obj.link.params.key && obj.link.params.key.icon) {
      delete obj.link.params.key.icon;
    }
    if (obj && obj.link.params.key && obj.link.params.key.iconCssStyle) {
      delete obj.link.params.key.iconCssStyle;
    }
    if (obj && obj.link.params.key && obj.link.params.key.cslLabel) {
      delete obj.link.params.key.cslLabel;
    }
    if (obj && obj.link.params.key && obj.link.params.key.cslCssStyle) {
      delete obj.link.params.key.cslCssStyle;
    }
    if (obj && obj.link.params.key && obj.link.params.key.cslLabelCssStyle) {
      delete obj.link.params.key.cslLabelCssStyle;
    }
  }


  requestForSubmit(submit, scanSub) {
    const that = this;
    if (!submit) {
      return; // 如果没有提交的数据，直接返回  
    }
    if (submit) {
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      this.httpService.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success === true) {
          if (that.jumpPageAfterSubmit) {
            if (res.target) {
              that.recycleCameraResource(scanSub, () => {
                setTimeout(() => {
                  const link = {
                    params: res.params,
                    target: res.target,
                    type: that.linkType
                  };
                  that.pageModalService.openPage(link);
                }, 50);
              });
            }
          } else {
            this.appGlobalService.showToast('核销成功！', 3500, 'middle');
          }
        } else {
          that.recycleCameraResource(scanSub);
          // 请求数据失败 还可以继续扫描
          that.appGlobalService.showToast(res.message, 3500, 'middle');
        }
        if (!that.jumpPageAfterSubmit) {
          setTimeout(() => {
            that.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
            // this.navController.back();
            that.appGlobalService.goBack();
          }, 2000);
        }
      });
    }
  }


  recycleCameraResource(scanSub, callBackFunction?) {
    const that = this;
    if (that.jumpPageAfterSubmit) {

      that.qrScanner.hide(); // hide camera preview
      scanSub.unsubscribe(); // stop scanning
      // this.navController.back();
      // that.appGlobalService.goBack();
      if (callBackFunction !== undefined) {
        setTimeout(() => {
          callBackFunction();
        }, 50);
      }

    }

  }





  ionViewWillEnter() {
    if (localStorage.getItem('client') === 'APP' &&
      (localStorage.getItem('platform') === 'android' || localStorage.getItem('platform') === 'ios')) {
      this.qrScanner.prepare()
        .then((status: QRScannerStatus) => {
          if (status.authorized) {
            console.log('start scanning');
            // start scanning
            const scanSub = this.qrScanner.scan().subscribe((text: string) => {
              console.log('Scanned success... =', text);
              if (this.routerParams && this.routerParams.codeEventName) {
                this.appGlobalService.eventService.eventEmit.emit(this.routerParams.codeEventName, text);
                console.log(' emit codeEventName success... name=', this.routerParams.codeEventName);

                if (this.routerParams && this.routerParams.disableAutoBack === undefined) {
                  setTimeout(() => {
                    this.appGlobalService.goBack();
                  }, 200);
                }
              } else {
                if (this.submit !== undefined) {
                  // 支持跳转页面
                  if (this.action && this.action === 'link') {
                    if (this.submit && this.submit.link) {
                      if (this.submit.link.params) {
                        // tslint:disable-next-line:no-string-literal
                        this.appGlobalService['express_no'] = text;
                        // tslint:disable-next-line:no-string-literal
                        this.submit.link.params['scan_code'] = text;
                        // tslint:disable-next-line:no-string-literal
                        this.submit.link.params['express_no'] = text;
                      }
                      if (this.submit.link.params.autoGotoSearchByNumberId) {
                        this.appGlobalService.goBack();
                        const domId = this.submit.link.params.autoGotoSearchByNumberId;
                        // 调用函数设置
                        if (document.getElementById(domId)) {
                          setTimeout(() => {
                            document.getElementById(domId).click();
                          }, 500);
                        }
                      } else {
                        this.pageModalService.openPage(this.submit.link);
                      }

                    }
                  } else {
                    // tslint:disable-next-line:no-string-literal
                    this.submit.content['scan_code'] = text;
                    if (this.submit.content.eventFiledName !== undefined
                      &&
                      this.submit.content.eventFiledName !== ''
                    ) {
                      this.submit.content[this.submit.content.eventFiledName] = text;
                    }
                    this.requestForSubmit(this.submit, scanSub);
                  }

                }
              }
              this.qrScanner.hide(); // hide camera preview
              scanSub.unsubscribe(); // stop scanning
            });
            // 打开摄像头
            this.qrScanner.show();
          } else if (status.denied) {
            console.log('没有摄像头权限，请前往设置中开启');
          } else {
            // permission was denied, but not permanently. You can ask for permission again at a later time.
            console.log('没有摄像头权限，请前往设置中开启');
          }
        })
        .catch((e: any) => console.log('Error is', e));
    }
  }
  /*页面可见后执行 */
  ionViewDidEnter() {
    this.isShow = true; // 显示背景
  }

  // 闪光灯控制，默认关闭
  toggleLight() {
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.light = !this.light;
  }

  // 前后摄像头互换
  toggleCamera() {
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.frontCamera = !this.frontCamera;
  }
  hideCamera() {
    this.qrScanner.hide(); // 需要关闭扫描，否则相机一直开着
    this.qrScanner.destroy(); // 关闭
  }
  ionViewWillLeave() {
    this.hideCamera();
  }

  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }

  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }

  // 返回方法
  back() {
    this.appGlobalService.goBack();
  }

  getNgStyle(value) {
    if (value) {
      const cssStyles = value.split(";");
      const newStyle = {};
      // tslint:disable-next-line:prefer-for-of
      for (let i = 0; i < cssStyles.length; i++) {
        const cssStrs = cssStyles[i].split(":");
        newStyle[cssStrs[0]] = cssStrs[1];
      }
      return newStyle;
    }
  }
}
